﻿// Our default grid options
var defaultGridOptions = {
    enableCellNavigation: true,
    enableColumnReorder: false,
    enableAddRow: false,
    editable: true,
    editOnDoubleClick: true,
    multiSelect: false,
    forceFitColumns: false,
    autoHeight: false,
    resizable: false,
    autoEdit: false,
    showHeaderRow: true,
    rowHeight: 36,
    headerHeight: 36,
    headerRowHeight: 36

};

// This function will run when the document has finished loading (not including images).
$().ready(function () {
    var lastSampleId = 0;
    var sampleGrid = setUpSampleGrid('#sampleGrid');
    // Turns all buttons with a class of "button" into fancy jQuery UI-themed buttons.
    $('.button').button();

    // Transform our sample div into a dialog box.
    $('#sampleDialog').dialog(
        {
            modal: true,
            resizable: false,
            autoOpen: false,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });

                        // Post to the server
                        $.post('/Sample/FakeSave',
                        // Set up the data to transfer
                            {
                            field1: $('#field1').val(),
                            field2: $('#field2').val()
                        },
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    sampleGrid.dataView.addItem({ id: lastSampleId++, Field1: response.Data.Field1, Field2: response.Data.Field2 });
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });
                        // Clear the fields
                        $('#field1').val('');
                        $('#field2').val('');

                        // Close the dialog
                        $(this).dialog('close');
                    },
                    Cancel:
                        function () {
                            // Clear the fields
                            $('#field1').val('');
                            $('#field2').val('');

                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });

    // Set up the button to automatically open the dialog box.
    $('#sampleDialogButton').click(function () {
        $('#sampleDialog').dialog('open');
    });
});

// Sets up the sample grid
function setUpSampleGrid(gridSelector) {
    // First, define the grid's columns
    var columns = [
            { id: "Field1", name: "Field 1", field: "Field1", showFilter: true, width: 100, sortable: true, editor: Slick.Editors.Text, validator: RequiredFieldValidator },
            { id: "Field2", name: "Field 2", field: "Field2", width: 240, sortable: true, showFilter: true, editor: Slick.Editors.Text, validator: RequiredFieldValidator },
            { id: "buttons", name: "", buttons: "Delete", width: 100, formatter: CellButtonFormatter }
        ];

    // Set up the delete button's functionality
    $(document).on('click', gridSelector + ' .slick-cell-button-Delete',
        function () {
            var row = grid.getDataItem(grid.getActiveCell().row);
            grid.dataView.deleteItem(row.id);
        });

    // Set some additional options
    var options = $.extend(true, {}, defaultGridOptions);
    options.hasHeaderFilters = true;

    var grid = new Slick.Grid(gridSelector, [], columns, options);
    grid.registerPlugin(new Slick.ExtendedGrid(gridSelector, columns, options));
    grid.updateHeaderRow();

    // Make the filters show up properly
//    grid.dataView.addItem({ id: 0 });
//    grid.dataView.setItems([]);
//    grid.invalidate();

    // Make the grid buttons use jQuery UI
    grid.onRender.subscribe(function (e, args) {
        $('.slick-cell-button').button();
    });

    // Return the grid object so we can store it in a variable
    return grid;
}

// Use this function to block the UI. Defaults to the saving block.
function block($element, blockSelector) {
    if (!blockSelector)
        blockSelector = '#savingBlock';
    if ($element)
        $($element).block({ message: $(blockSelector), css: { 'font-size': '20px', width: '200px', height: '30px', 'line-height': '30px', border: '3px solid #000'} });
    else
        $.blockUI({ message: $(blockSelector), css: { 'font-size': '20px', width: '200px', height: '30px', 'line-height': '30px', border: '3px solid #000'} }).center();

}

// Use this function to unblock the UI.
function unblock($element) {
    if ($element)
        $($element).unblock();
    else
        $.unblockUI();
}
